#!/bin/bash

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INSTALL_DIR="/opt/x11vnc"

echo "x11vnc 安装脚本"
echo "==============="

# 检查权限
if [ "$EUID" -ne 0 ]; then
    echo "错误: 需要root权限安装到系统目录"
    echo "请使用: sudo $0"
    exit 1
fi

# 创建安装目录
mkdir -p "$INSTALL_DIR"

# 复制文件
echo "复制文件到 $INSTALL_DIR..."
cp -r "$SCRIPT_DIR/../bin" "$INSTALL_DIR/"
cp -r "$SCRIPT_DIR/../lib" "$INSTALL_DIR/"
cp -r "$SCRIPT_DIR/../include" "$INSTALL_DIR/"
cp -r "$SCRIPT_DIR/../doc" "$INSTALL_DIR/"
cp -r "$SCRIPT_DIR" "$INSTALL_DIR/scripts"

# 创建符号链接
ln -sf "$INSTALL_DIR/bin/x11vnc" /usr/local/bin/x11vnc

# 设置权限
chmod +x "$INSTALL_DIR/bin/x11vnc"
chmod +x "$INSTALL_DIR/scripts"/*.sh

# 安装systemd服务（可选）
read -p "是否安装systemd服务? [y/N]: " install_service
if [[ $install_service =~ ^[Yy]$ ]]; then
    cp "$SCRIPT_DIR/x11vnc.service" /etc/systemd/system/
    systemctl daemon-reload
    echo "systemd服务已安装，使用以下命令管理："
    echo "  启动: systemctl start x11vnc"
    echo "  停止: systemctl stop x11vnc"
    echo "  开机自启: systemctl enable x11vnc"
fi

echo "安装完成！"
echo "x11vnc已安装到: $INSTALL_DIR"
echo "启动命令: x11vnc -display :0"
echo "或使用脚本: $INSTALL_DIR/scripts/start-x11vnc.sh"
